package com.atguigu.tingshu.account.consumer;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 账户初始化消费者
 *
 * @author Taeyang
 * @date 2025/4/27
 */
@Component
@Log4j2
public class AccountInitConsumer {

    private final UserAccountService userAccountService;

    @Autowired
    public AccountInitConsumer(UserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    /**
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "account_queue")
    public void accountInitConsumer(Channel channel, Message message) {
        // 获取消息的编号
        String msg = new String(message.getBody());
        // 获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            // 初始化账户
            userAccountService.initAccount(Long.valueOf(msg));
            // 确认消息：1. 消息的编号，2. 消息是否批量确认
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            // 消费消息失败，拒绝消费（单条拒绝），两次机会，getRedelivered 是否被拒绝过
            if (messageProperties.getRedelivered()) {
                // 不是第一次
                log.error("消息连续两次都消费失败，失败原因：{}", e.getMessage());
                channel.basicReject(deliveryTag, false);

            } else {
                // 第一次
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
